package com.aebiz.usercenter.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aebiz.usercenter.auth.pojo.ARoleMenu;
import com.aebiz.usercenter.auth.service.IAuthService;
import com.aebiz.usercenter.common.controller.IBaseController;
import com.aebiz.usercenter.common.util.ConstatFinalUtil;
import com.aebiz.usercenter.common.util.PageInfoUtil;
import com.aebiz.usercenter.users.pojo.AAdmins;
import com.aebiz.usercenter.users.pojo.ARole;
import com.aebiz.usercenter.users.service.IUsersService;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("/back/admins")
public class AdminsBackController extends IBaseController{

	@Resource
	private IUsersService usersService;
	@Resource
	private IAuthService authService;
	
	/**
	 * 登陆后的首页
	 * @return
	 */
	@RequestMapping("/main")
	public String main()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--main--");
		return "/back/admins/main";
	}
	/**
	 * 登陆后的首页
	 * @return
	 */
	@RequestMapping("/leftMenu")
	public String leftMenu()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--leftMenu--");
		return "/back/admins/leftMenu";
	}
	
	/**
	 * 退出
	 * @returnmain.jsp
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--logout--");
		/* 删除session中的信息 */
		session.removeAttribute("admins");
		return "redirect:/login.htm" ; 
	}
	
	/*---- 管理员模块开始 ----*/
	/**
	 * 管理员列表
	 * @return
	 */
	@RequestMapping("/adminsList")
	public String adminsList(String keyword,String status,String st,String ed,Model model,
			String currentPage,String pageSize){
		ConstatFinalUtil.SYS_LOGGER.info("-------adminsList--------");
		if(st==null){
			st="";
		}
		if(ed==null){
			ed="";
		}
		if(status==null){
			status="";
		}
		Map<String, Object> condMap=new HashMap<>();
			condMap.put("keyword", keyword);
		if(!"".equalsIgnoreCase(status)){
			condMap.put("status", status);
		}
		Date stDate=null;
		Date edDate=null;
		if(!"".equalsIgnoreCase(st)&&!"".equalsIgnoreCase(ed)){
			stDate=this.dateFormatUtil.strDateTime(st);
			edDate=this.dateFormatUtil.strDateTime(ed);
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		
		PageInfoUtil pageInfoUtil=proccedPageInfo(currentPage, pageSize);
		Map resultMap = this.usersService.findCondListAdminsService(pageInfoUtil,condMap);
		List<AAdmins> adminsList = (List<AAdmins>) resultMap.get("list");
		pageInfoUtil = (PageInfoUtil) resultMap.get("pageInfoUtil");
		model.addAttribute("adminsList", adminsList);
		model.addAttribute("pageInfoUtil", pageInfoUtil);
		
		/* 将查询条件放到request中 */
		model.addAttribute("keyword", keyword);
		model.addAttribute("status", status);
		model.addAttribute("st", st);
		model.addAttribute("ed", ed);
		return "/back/admins/adminsList";
	}
	
	/**
	 * 打开管理员添加页面
	 * @return
	 */
	@RequestMapping("/adminsInsert")
	public String adminsInsert(Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--adminsInsert--");
		
		/* 查询所有启用的角色 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("status", "1");
		List<ARole> roleList = this.usersService.findCondListRoleService(null, condMap);
		model.addAttribute("roleList", roleList);
		return "/back/admins/adminsInsert"; 
	}
	
	/*---- 管理员模块结束 ----*/
	/*---- 菜单模块开始 ----*/
	@RequestMapping("/menuTreeList")
	public String menuTreeList(Model model){
		ConstatFinalUtil.SYS_LOGGER.info("--menuTreeList--");
		/* 生成树形结构的字符串 */
		String result = this.authService.proccedMenuTreeStr("menu","");
		/* 存储字符串 */
		model.addAttribute("result", result);
		return "/back/admins/menuTreeList" ; 
	}
	/*---- 菜单模块结束 ----*/
	

	/*---- 权限分配开始 ----*/
    
	/**
	 * 权限分配页面
	 * @return
	 */
	@RequestMapping("/roleMenuInsert")
	public String roleMenuInsert(String roleId,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--roleMenuInsert--");
		
		/* 生成树形结构的字符串 */
		String result = this.authService.proccedMenuTreeStr("roleMenu",roleId);
		/* 存储字符串 */
		model.addAttribute("result", result);
		return "/back/admins/roleMenuInsert" ; 
	}
	/**
	 * 权限分配提交
	 * 获取前台有哪些复选框被选中，前台选择了就是数据库中有数据，没有被选择就是null
	 * 往中间表加数据，加数据之前，先删除老数据
	 * 提示信息:操作成功,总条数:{},成功:{},失败:{}
	 * @param request
	 * @param menuId
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value="/roleMenuInsertSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String roleMenuInsertSubmit(HttpServletRequest request,String[] menuId,String roleId)
	{
	    ConstatFinalUtil.SYS_LOGGER.info("=====roleMenuInsertSubmit===========menuId:{}========",Arrays.toString(menuId));
	    /*默认值*/
	    this.info="操作失败";
	    if(menuId!=null)
	    {
	    	int totalCount=menuId.length;
	    	int succedCount=0;
	    	int failedCount=0;
	    	
	    	/*删除老数据*/
	    	Map<String, Object> condMap=new HashMap<>();
	    	condMap.put("roleId", roleId);
	    	this.authService.deleteOneRoleMenuService(condMap);
	    	/*增加新数据*/
	    	for (int i = 0; i < menuId.length; i++) {
				String menId=menuId[i];
				try {
					/* 往中间表(角色菜单表)增加数据, */
					ARoleMenu roleMenu=new ARoleMenu();
					roleMenu.setMenuId(Integer.valueOf(menId));
					roleMenu.setRoleId(Integer.valueOf(roleId));
					roleMenu.setCreateTime(new Date());
					roleMenu.setUpdateTime(new Date());
					roleMenu.setPubTime(new Date());
					JSONObject resultDbJson=this.authService.saveOneRoleMenuService(roleMenu);
					if("0".equalsIgnoreCase(resultDbJson.getString("code")))
					{
						succedCount ++ ; 
					}else
					{
						failedCount ++ ; 
					}
				} catch (Exception e) {
					failedCount ++ ; 
				}
			}
	    	/* 拼装提示信息 */
			this.info = "操作成功,总条数:" + totalCount + ",成功:" + succedCount + ",失败:" + failedCount;
	    }
	    ConstatFinalUtil.SYS_LOGGER.info("权限分配:信息:{},roleId:{},菜单:{}",this.info,roleId,Arrays.toString(menuId));
	    JSONObject resultJSON=this.printJuiJson(request,info);
	    return resultJSON.toJSONString();
	}
	/*---- 权限分配结束 ----*/
}
